package com.mifengs.mall.ui.login;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.ChatClient;
import com.hyphenate.helpdesk.callback.Callback;
import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.entity.ResponseBean;
import com.mifengs.mall.entity.TokenBean;
import com.mifengs.mall.event.LoginEvent;
import com.mifengs.mall.netWork.NetWork;
import com.mifengs.mall.widget.VerifyCodeView;
import com.tencent.android.tpush.XGPushConfig;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CompletePasswordActivity extends BaseActivity {

    @BindView(R.id.et_code)
    EditText mEtCode;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.iv_eye)
    ImageView mIvEye;
    @BindView(R.id.code_btn)
    Button mCodeBtn;
    @BindView(R.id.ll_code)
    RelativeLayout mLlCode;
    @BindView(R.id.code_btn_text)
    TextView mCodeBtnText;
    @BindView(R.id.code_time)
    TextView mCodeTime;
    @BindView(R.id.llayout_pwd)
    LinearLayout llayoutPwd;
    @BindView(R.id.pwd_explain_text)
    TextView pwdExplainText;
    @BindView(R.id.et_verity_code)
    EditText mEtVerityCode;
    @BindView(R.id.btn_photo_code)
    VerifyCodeView mPhotoCodeWebView;


    private String mPhoneNum;
    private boolean mDisplayFlg = false;
    private String mWeixinJson;
    private MyTime mTime;
    private int isRegType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complete_password);
        ButterKnife.bind(this);
        setStatusColorAndMode(R.color.white, true);
        initNavigationBar(true, "完善登录密码");
        init();
    }

    private void init() {
        mPhotoCodeWebView.loadUrl(Constant.PHONE_CODE);
        mPhotoCodeWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mPhotoCodeWebView.reload();
                return false;
            }
        });
        mPhoneNum = getIntent().getStringExtra("mobile");
        mWeixinJson = getIntent().getStringExtra("weixinJson");
        isRegType = getIntent().getIntExtra("isRegType", 1);
        mTime = new MyTime(60000, 1000);
        if (isRegType == 0) {
            llayoutPwd.setVisibility(View.GONE);
            pwdExplainText.setVisibility(View.GONE);
        } else {
            llayoutPwd.setVisibility(View.VISIBLE);
            pwdExplainText.setVisibility(View.VISIBLE);
        }
    }


    private void passwordTransformation() {

        if (!mDisplayFlg) {
            // display password text, for example "123456"
            mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        mDisplayFlg = !mDisplayFlg;

        mEtPassword.postInvalidate();

        if (mDisplayFlg) {
            mIvEye.setImageResource(R.drawable.ic_input_xianshi);
        } else {
            mIvEye.setImageResource(R.drawable.ic_input_noxianshi);
        }

    }

    @OnClick({R.id.code_btn, R.id.iv_eye, R.id.bt_complete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.code_btn:
                sendSMSCode();
                break;
            case R.id.iv_eye:
                passwordTransformation();
                break;
            case R.id.bt_complete:
                weixinRegByPhone();
                break;
        }
    }


    public void sendSMSCode() {

        String verifyCode = mEtVerityCode.getText().toString();

        if(TextUtils.isEmpty(verifyCode)){
            showLongToast("请输入图形验证码");
            return;
        }

        showLoading();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("mobile", mPhoneNum);
        hashMap.put("isBindType", "0");
        hashMap.put("randNum",verifyCode);
        NetWork.getLoginApi().sendSMSCodeRegister(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ResponseBean<TokenBean>>bindToLife())
                .subscribe(new Observer<ResponseBean<TokenBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        showLongToast(throwable.toString());
                        hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean<TokenBean> responseBean) {
                        hideLoading();
                        String status = responseBean.getStatus();
                        if (status.equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("验证码发送成功，请注意查收短信", Toast.LENGTH_SHORT);
                            startCountDownTime();
                        } else {
                            showLongToast(responseBean.getInfo());
                        }
                    }
                });
    }


    public void startCountDownTime() {
        mTime.start();
        mLlCode.setVisibility(View.VISIBLE);
        mCodeBtn.setVisibility(View.GONE);
    }


    public void weixinRegByPhone() {
        HashMap<String, Object> hashMap = new HashMap<>();


        String code = mEtCode.getText().toString();
        String pwd = mEtPassword.getText().toString();

        if (TextUtils.isEmpty(code)) {
            showLongToast("请输入验证码");
            return;
        }

        if (isRegType == 1) {
            if (TextUtils.isEmpty(pwd)) {
                showLongToast("请输入密码");
                return;
            }
        }


        hashMap.put("mobile", mPhoneNum);
        hashMap.put("password", pwd);
        hashMap.put("mobileCode", code);

        String pushToken = XGPushConfig.getToken(getContext());
        if (!TextUtils.isEmpty(pushToken)) {
            hashMap.put("usertoken", pushToken);
        }
        hashMap.put("jsonString", mWeixinJson);
        hashMap.put("mobiletype", "1");
        hashMap.put("isRegType", isRegType);
        NetWork.getLoginApi().weixinRegByPhone(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ResponseBean<TokenBean>>bindToLife())
                .subscribe(new Observer<ResponseBean<TokenBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        showLongToast(throwable.toString());
                    }

                    @Override
                    public void onNext(ResponseBean<TokenBean> tokenBeanResponseBean) {
                        String status = tokenBeanResponseBean.getStatus();
                        if (status.equals(Constant.SUCCESS_CODE)) {
                            LogUtil.i("token:",tokenBeanResponseBean.getParamer().getLoginToken());
                            PreferenceUtils.saveToken(tokenBeanResponseBean.getParamer().getLoginToken());
                            PreferenceUtils.saveUserMobile(MallApplication.getInstance(), mPhoneNum);
                            String hxName = "mfsc" + mPhoneNum.substring(3, mPhoneNum.length());
                            PreferenceUtils.saveHxUserName(MallApplication.getInstance(), hxName);
                            PreferenceUtils.saveHxUserPwd(MallApplication.getInstance(), "mifengs");
                            if (!ChatClient.getInstance().isLoggedInBefore()) {
                                hxCecLogin();
                            }
                            showLongToast("登录成功");
                            EventBus.getDefault().post(new LoginEvent(LoginEvent.LOGIN_SUCCESS));
                            finish();
                        } else {
                            showLongToast(tokenBeanResponseBean.getInfo());
                        }
                    }
                });
    }


    public void hxCecLogin() {
        String userName = PreferenceUtils.getHxUserName(MallApplication.getInstance());
        String userPwd = PreferenceUtils.getHxUserPwd(MallApplication.getInstance());
        if (!"".equals(userName) && !"".equals(userPwd)) {
            ChatClient.getInstance().login(userName, userPwd, new Callback() {
                @Override
                public void onSuccess() {
//                mView.hxCecLoginSuccess();
                }

                @Override
                public void onError(int i, String s) {
//                    ToastUitl.show(s, Toast.LENGTH_SHORT);
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });
        }
    }


    class MyTime extends CountDownTimer {

        public MyTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Date date = new Date(millisUntilFinished);
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
            String str = sdf.format(date);
//            System.out.println(str);
            mCodeTime.setText("(" + millisUntilFinished / 1000 + "s" + ")");
        }

        @Override
        public void onFinish() {
            mLlCode.setVisibility(View.GONE);
            mCodeBtn.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void finish() {
        if (mTime != null) {
            mTime.cancel();
        }
        super.finish();
    }
}
